const Koa = require('koa');
const KoaRouter = require('koa-router');
const webpack = require('webpack');
const currentIp = require('ip').address();

const open = require('open');
const loggerMiddleware = require('koa-logger')();
const convert = require('koa-convert');
const koaCompress = require('koa-compress')();
const webpackDevMiddleware = require('koa-webpack-dev-middleware');
const webpackHotMiddleware = require('koa-webpack-hot-middleware');

const config = require('../config/config');
const webpackDevConfig = require('../config/webpack.config.dev');
const compiler = webpack(webpackDevConfig);

const app = new Koa();
const uri = 'http://' + currentIp + ':' + config.devServer.port;

const devMiddleware = webpackDevMiddleware(compiler, {
    publicPath: webpackDevConfig.output.publicPath,
    headers: {'Access-Control-Allow-Origin': '*'},
    stats: {
        colors: true,
        modules: false,
    },
    noInfo: false,
})

// 中间件，一组async函数,generator函数需要convert转换
const middlewares = [
    loggerMiddleware,
    koaCompress,    // 压缩响应
    convert(devMiddleware),
    convert(webpackHotMiddleware(compiler)),
    KoaRouter().middleware(), // 路由
]
middlewares.forEach((middleware) => {
    if (!middleware) return;
    app.use(middleware);
})

console.log('> Starting dev server ...');
devMiddleware.waitUntilValid(() => {
    console.log('> Listening at ' + uri + '\n');
    open(uri);
})

// 错误处理
app.on('error', (err) => {
    console.error('Server error: \n%s\n%s ', err.stack || '');
})

app.listen(config.devServer.port);